import config from '@/config.js'
import { t } from '@/locale/index'
import { requestHeader, debounce } from '@/common/util'

// 使用  uni.request 封装请求，返回 Promise，get post put delete
const request = (url, method, params = {}, {hmsg, hload} = {}) => {
  let baseUrl = config.apiBaseUrl

  // #ifdef H5
  // baseUrl = 'api/'
  // #endif

  if (hload) {
    uni.showLoading({
      title: t('common.load_ing'),
      mask: true
    });
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method: method,
      data: params,
      header: requestHeader(),
      success: (res) => {
        if (res.statusCode == 401) {
          uni.removeStorageSync('account')
        }

        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res.data);
          if (!hmsg) {
            if (res.statusCode == 401) {
              if (method != 'GET') {
                uni.showToast({ title: res.data.error, icon: 'none' })
              }
              return;
            }

            if (res.data.message) {
              uni.showToast({ title: res.data.message, icon: 'none' })
            }
          }
        }
      },
      fail: (err) => {
		  console.log("接口报错",err);
        reject(err);
      },
      complete: (res) => {
        uni.hideLoading();
        uni.stopPullDownRefresh()
      }
    });
  });
}

const get = (url, params, { hmsg, hload = true } = {}) => {
  return request(url, 'GET', params, { hmsg, hload });
}

const post = (url, params, { hmsg, hload = true } = {}) => {
  return request(url, 'POST', params, { hmsg, hload });
}

const put = (url, params, { hmsg, hload = true } = {}) => {
  return request(url, 'PUT', params, { hmsg, hload });
}

const del = (url, params, { hmsg, hload = true } = {}) => {
  return request(url, 'DELETE', params, { hmsg, hload });
}

export default {
  get,
  post,
  put,
  del,
}


